package com.wejoy.video.middle.station.data.service.evs.impl;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.constant.RedisKeys;
import com.wejoy.video.middle.station.data.domain.system.SysDept;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.util.baiduevs.EvsApiHttpUtils;
import com.wejoy.video.middle.station.data.vo.api.BusinessPointConfigVO;
import com.wejoy.video.middle.station.data.vo.evsapi.EvsApiLoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author miracle_j
 * Create by 2024/3/21 4:28 PM
 */
@Service
public class EvsHttpServiceImpl implements IEvsHttpService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<SysDept> getDepartments(SysDept sysDept, String token){
        JSONObject jsonObject = EvsApiHttpUtils.getDepartments(sysDept.getParentId(),sysDept.getIncludeLower(),sysDept.getName(),token);
        return JSONArray.parseArray(jsonObject.getString("data"), SysDept.class);
    }

    @Override
    public JSONArray getDepartmentsJson(SysDept sysDept, String token){
        JSONObject jsonObject = EvsApiHttpUtils.getDepartments(sysDept.getParentId(),sysDept.getIncludeLower(),sysDept.getName(),token);
        return jsonObject.getJSONArray("data");
    }

    @Override
    public JSONObject getUsers(Integer departmentId, Integer pageNo, Integer PageSize, String name, String tel, String token) {
        JSONObject jsonObject = EvsApiHttpUtils.getUsers(departmentId,pageNo,PageSize,name,tel,token);
        return jsonObject;
    }

    @Override
    public JSONObject getUserById(Long id, String token){
        return EvsApiHttpUtils.getUserById(id.intValue(), token);
    }

    @Override
    public HttpResponse evsLogin(EvsApiLoginVO loginVO){
        return EvsApiHttpUtils.evsLogin(loginVO);
    }
    @Override
    public JSONObject getCurrentUserInfo(String token){
        return EvsApiHttpUtils.getCurrentUserInfo(token);
    }

    @Override
    public JSONObject getPoints(String token,Integer pageSize,Integer pageNo,Integer departmentId,String pointName,Boolean includeLowerArea){
        return EvsApiHttpUtils.getPoints(token,pageSize,pageNo,departmentId,pointName,includeLowerArea);
    }

    @Override
    public JSONObject getPointsById(String token, Integer pointId) {
        return EvsApiHttpUtils.getPointsById(token,pointId);
    }

    @Override
    public JSONObject pointsSignedUrl(String token,Integer pointId,String protocol){
        return EvsApiHttpUtils.pointsSignedUrl(token,pointId,protocol);
    }
    //getPointTagInfo
    @Override
    public JSONObject getPointTagInfo(String token, Long tagId, Integer pageNo, Integer pageSize){
        return EvsApiHttpUtils.getPointTagInfo(token,tagId,pageNo,pageSize);
    }

    @Override
    public JSONObject getTags(String token, Long parentId,String tagCategoryId){
        return EvsApiHttpUtils.getTags(token,parentId,tagCategoryId);
    }

    @Override
    public JSONObject getPointTagInfoByPointId(String token, Long parentId, Long pointId, Integer pageNo, Integer pageSize){
        return EvsApiHttpUtils.getPointTagInfoByPointId(token,parentId,pageNo,pointId,pageSize);
    }

    @Override
    public JSONObject getPointInfo(String token,Long pointId){
        return EvsApiHttpUtils.getPointInfo(token,pointId);
    }

    @Override
    public JSONObject getPointConfig(String sceneType,String abilityType,Integer pointId,String token){
        return EvsApiHttpUtils.getPointConfig(sceneType,abilityType,pointId,token);
    }

    @Override
    public JSONObject getCloudRecordList(String token, Integer pointId, Integer pageSize, Integer pageNo, String startTime, String endTime) {
        return EvsApiHttpUtils.getCloudRecordList(token,pointId,pageSize,pageNo,startTime,endTime);
    }

    @Override
    public JSONObject getLocalRecordList(String token, Integer pointId,String startTime, String endTime) {
        return EvsApiHttpUtils.getLocalRecordList(token,pointId,startTime,endTime);
    }

    @Override
    public JSONObject businessHallPointConfig(String sceneType,String abilityType,BusinessPointConfigVO businessPointConfigVO,String token){
        return EvsApiHttpUtils.businessHallPointConfig(sceneType,abilityType,businessPointConfigVO,token);
    }

    @Override
    public JSONObject fi(String token, Integer pointId, String fiCommand, Integer speed){
        return EvsApiHttpUtils.fi(token,pointId,fiCommand,speed);
    }

    @Override
    public JSONObject putPtz(String token, Integer pointId, String ptzCommand, Integer speed){
        return EvsApiHttpUtils.putPtz(token,pointId,ptzCommand,speed);
    }


    /**
     * 获取会话token
     * @return
     */
    @Override
    public String getToken() {
        String token = (String) redisTemplate.opsForValue().get(RedisKeys.SCREEN_API_TOKEN);

        if (StringUtils.isEmpty(token)) {
            token = loginAndRetrieveToken();
        } else {
            JSONObject currentUserInfo = EvsApiHttpUtils.getCurrentUserInfo(token);
            String redirect = currentUserInfo.getString("redirect");

            if (!StringUtils.isEmpty(redirect)) {
                token = loginAndRetrieveToken();
            }
        }

        return token;
    }

    private String loginAndRetrieveToken() {
        HttpResponse httpResponse = EvsApiHttpUtils.evsLoginCurrent();
        JSONObject result = JSONObject.parse(httpResponse.body());

        if (!StringUtils.isEmpty(result.getString("code"))) {
            throw new BusinessException(result.getString("message"));
        }

        String header = httpResponse.header("Set-Cookie");
        String token = extractSessionValue(header);

        redisTemplate.opsForValue().set(RedisKeys.SCREEN_API_TOKEN, token);

        return token;
    }

    private String extractSessionValue(String input) {
        // 使用正则表达式提取SAAS_SESSION的值
        Pattern pattern = Pattern.compile("SAAS_SESSION=([^;]+)");
        Matcher matcher = pattern.matcher(input);
        // 检查是否有匹配
        if (matcher.find()) {
            // 返回匹配的值
            return matcher.group(1);
        } else {
            throw new BusinessException("未检出session");
        }
    }

}
